using System;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;

namespace Aurora.TaskScheduler.Dashboard.Middleware;

/// <summary>
/// 权限认证中间件
/// </summary>
public class BasicAuthMiddleware
{
    private readonly RequestDelegate _next;
    private readonly DashboardOptions _options;

    public BasicAuthMiddleware(RequestDelegate next, IOptions<DashboardOptions> options)
    {
        _next = next;
        _options = options.Value;
    }

    /// <summary>
    /// 执行
    /// </summary>
    /// <param name="context"></param>
    public async Task InvokeAsync(HttpContext context)
    {
        // 拦截quartz ui 开头的访问
        if (context.Request.Path.StartsWithSegments(_options.PathBase))
        {
            string authHeader = context.Request.Headers["Authorization"];
            if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Basic "))
            {
                //帐户密码读取并解码
                var encodedUsernamePassword =
                    authHeader.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries)[1]?.Trim();
                var decodedUsernamePassword =
                    Encoding.UTF8.GetString(Convert.FromBase64String(encodedUsernamePassword));

                string userName = decodedUsernamePassword.Split(":", 2)[0];
                string password = decodedUsernamePassword.Split(":", 2)[1];
                if (IsAuthorized(userName, password))
                {
                    await _next.Invoke(context);
                    return;
                }
            }

            context.Response.Headers["WWW-Authenticate"] = "Basic";
            context.Response.StatusCode = HttpStatusCode.Unauthorized.GetHashCode();
        }
        else
        {
            await _next.Invoke(context);
        }
    }


    /// <summary>
    /// 设置密码
    /// </summary>
    /// <param name="username"></param>
    /// <param name="password"></param>
    /// <returns></returns>
    private bool IsAuthorized(string username, string password)
    {
        // 从配置读取帐户密码,否则默认
        var configUserName = _options.DefaultUserName ?? "Admin";
        var configPassword = _options.DefaultPassword ?? "123456";
        return username.Equals(configUserName, StringComparison.InvariantCultureIgnoreCase)
               && password.Equals(configPassword);
    }
}